﻿function showTab(tabId) {
  const loginTab = document.getElementById('login');
  const registerTab = document.getElementById('register');
  if (tabId === 'login') {
    loginTab.style.display = 'block';
    registerTab.style.display = 'none';
  } else {
    loginTab.style.display = 'none';
    registerTab.style.display = 'block';
  }
}

const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');

loginForm.addEventListener('submit', function (e) {
  e.preventDefault();
  const username = document.getElementById('loginUsername').value;
  const password = document.getElementById('loginPassword').value;
  // 简单验证用户名和密码非空（可补充更多前端验证规则）
  if (username === "" || password === "") {
    alert("用户名和密码不能为空");
    return;
  }
  // 发送AJAX请求到后端进行登录验证，此处使用fetch API示例，可根据需求换用其他方式如axios等
  fetch('login.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
  }).then(response => response.json()).then(data => {
    if (data.success) {
      alert("登录成功");
      
      // 这里可添加登录成功后的页面跳转等操作逻辑
      cacheUserInfo(username, data.userid);
      window.location.href = "friends/index.html";
    } else {
      alert("用户名或密码错误");
    }
  });
});

function cacheUserInfo(name, id) {
  let user = {
    name: name,
    id: id
  }
  localStorage.setItem("user", JSON.stringify(user));
}
registerForm.addEventListener('submit', function (e) {
  e.preventDefault();
  const username = document.getElementById('registerUsername').value;
  const password = document.getElementById('registerPassword').value;
  const userid = Date.now();
  const confirmPassword = document.getElementById('registerConfirmPassword').value;
  // 验证用户名、密码非空以及密码一致性（可补充更多前端验证规则）
  if (username === "" || password === "" || confirmPassword === "") {
    alert("所有字段都不能为空");
    return;
  }
  if (password !== confirmPassword) {
    alert("两次输入的密码不一致");
    return;
  }
  // 发送AJAX请求到后端进行注册操作
  fetch('register.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&userid=${encodeURIComponent(userid)}`
  }).then(response => response.json()).then(data => {
    if (data.success) {
      cacheUserInfo(username, userid);
      alert("注册成功");
      window.location.href = "friends/index.html";
      // 可添加注册成功后自动切换到登录页面等逻辑，如showTab('login');
    } else {
      alert("注册失败，用户名可能已存在等原因");
    }
  });
});